<template>
  <el-config-provider :locale="zhCn">
    <div class="staff-manage">
      <!-- 筛选条件区域 -->
      <filter-form v-model="filterForm" :form-items="formItems" @search="handleSearch" @reset="resetFilter" />

      <!-- 操作按钮区域 -->
      <div class="operation-section">
        <el-button type="primary" @click="handleAdd">新增员工</el-button>
      </div>

      <!-- 列表展示区域 -->
      <div class="table-section">
        <el-table :data="tableData" border style="width: 100%" v-loading="loading" class="custom-table">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column label="头像" width="80" align="center">
            <template #default="{ row }">
              <el-avatar :size="40" :src="row.avatar || defaultAvatar" />
            </template>
          </el-table-column>
          <el-table-column prop="userName" label="员工账号" min-width="100" show-overflow-tooltip />
          <el-table-column prop="nickName" label="昵称" min-width="100" show-overflow-tooltip />
          <el-table-column prop="dept.deptName" label="所属部门" min-width="120" show-overflow-tooltip />
          <el-table-column prop="phonenumber" label="手机号码" min-width="120" show-overflow-tooltip />
          <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
          <el-table-column prop="sex" label="性别" width="80" align="center">
            <template #default="{ row }">
              {{ row.sex === '0' ? '男' : '女' }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === '0' ? 'success' : 'danger'">
                {{ row.status === '0' ? '正常' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="userGrade" label="用户等级" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.userGrade === '1' ? 'warning' : 'info'">
                {{ row.userGrade === '1' ? '管理员' : '用户' }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="loginIp" label="最后登录IP" min-width="120" show-overflow-tooltip />
          <el-table-column prop="loginDate" label="最后登录时间" min-width="180" show-overflow-tooltip />
          <el-table-column prop="createTime" label="创建时间" min-width="180" show-overflow-tooltip />
          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total" @pagination="handlePagination" />

      <!-- 新增/编辑员工对话框 -->
      <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增员工' : '编辑员工'" width="500px" destroy-on-close class="staff-dialog">
        <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px" class="staff-form">
          <el-form-item label="所属部门" prop="deptId">
            <el-tree-select
              v-model="form.deptId"
              :data="deptList"
              :props="{
                label: 'deptName',
                value: 'deptId',
                children: 'children'
              }"
              placeholder="请选择部门"
              class="w-full"
              check-strictly
              :render-after-expand="false"
              @change="handleDeptChange"
            />
          </el-form-item>
          <el-form-item label="员工账号" prop="userName">
            <el-input v-model="form.userName" placeholder="请输入员工账号" />
          </el-form-item>
          <el-form-item label="昵称" prop="nickName">
            <el-input v-model="form.nickName" placeholder="请输入昵称" />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input v-model="form.phonenumber" placeholder="请输入手机号码" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="form.sex">
              <el-radio label="0">男</el-radio>
              <el-radio label="1">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </el-config-provider>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { getEmployeeList, addEmployee, editEmployee, deleteEmployee } from '@/api/companyMange/staffMange';
import type { Employee, AddEmployeeParams, EditEmployeeParams } from '@/api/companyMange/staffMange';
import { getDepartmentList } from '@/api/companyMange/departmentMange';
import type { Department } from '@/api/companyMange/departmentMange';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import FilterForm from '@/components/FilterForm/index.vue';
import Pagination from '@/components/Pagination/index.vue';
import type { FormItem } from '@/components/FilterForm/index.vue';
import defaultAvatar from '@/assets/avatar.jpg';

// 接口响应类型定义
interface DeptListResponse {
  code: number;
  msg: string;
  data: Department[];
}

interface CommonResponse {
  code: number;
  msg: string;
  [key: string]: any;
}

// 筛选表单
interface FilterFormType {
  userName: string;
  phonenumber: string;
  status: string;
  [key: string]: string; // 添加索引签名
}

const filterForm = reactive<FilterFormType>({
  userName: '',
  phonenumber: '',
  status: ''
});

// 表单项配置
const formItems: FormItem[] = [
  {
    type: 'input',
    label: '员工账号',
    prop: 'userName',
    placeholder: '请输入员工账号',
    clearable: true
  },
  {
    type: 'input',
    label: '手机号码',
    prop: 'phonenumber',
    placeholder: '请输入手机号码',
    clearable: true
  },
  {
    type: 'select',
    label: '状态',
    prop: 'status',
    placeholder: '请选择状态',
    clearable: true,
    options: [
      { label: '正常', value: '0' },
      { label: '停用', value: '1' }
    ]
  }
];

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 加载状态
const loading = ref(false);

// 表格数据
const tableData = ref<Employee[]>([]);

// 部门列表
const deptList = ref<Department[]>([]);

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref<'add' | 'edit'>('add');
const formRef = ref();

// 表单数据
interface FormData extends Omit<AddEmployeeParams, 'deptId'> {
  userId?: string | number;
  deptId?: number;
  deptName?: string;
  userName: string;
  nickName: string;
  phonenumber: string;
  email: string;
  sex: string;
}

const form = reactive<FormData>({
  userId: '',
  deptId: undefined,
  deptName: '',
  userName: '',
  nickName: '',
  phonenumber: '',
  email: '',
  sex: '0'
});

// 表单校验规则
const formRules = {
  deptId: [{ required: true, message: '请选择所属部门', trigger: 'change' }],
  userName: [{ required: true, message: '请输入员工账号', trigger: 'blur' }],
  nickName: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  phonenumber: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  sex: []
};

// 将扁平数据转换为树形结构
const convertToTree = (data: Department[]) => {
  const result: Department[] = [];
  const map: { [key: string | number]: Department } = {};

  // 先将数据转换为map
  data.forEach((item) => {
    map[item.deptId] = { ...item, children: [] };
  });

  // 构建树形结构
  data.forEach((item) => {
    const node = map[item.deptId];
    if (item.parentId === 0) {
      result.push(node);
    } else {
      if (map[item.parentId]) {
        map[item.parentId].children?.push(node);
      }
    }
  });

  return result;
};

// 获取部门列表
const getDeptList = async () => {
  try {
    const res = (await getDepartmentList({})) as unknown as DeptListResponse;
    if (res.code === 200) {
      deptList.value = convertToTree(res.data);
    } else {
      ElMessage.error(res.msg || '获取部门列表失败');
    }
  } catch (error) {
    console.error('获取部门列表失败:', error);
    ElMessage.error('获取部门列表失败');
  }
};

// 处理分页变化
const handlePagination = ({ pageNum, pageSize: size }: { pageNum: number; pageSize: number }) => {
  currentPage.value = pageNum;
  pageSize.value = size;
  getList();
};

// 获取员工列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await getEmployeeList({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...filterForm
    });

    if (res.code === 200) {
      tableData.value = res.rows;
      total.value = res.total;
    } else {
      ElMessage.error(res.msg || '获取员工列表失败');
    }
  } catch (error) {
    console.error('获取员工列表失败:', error);
    ElMessage.error('获取员工列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = (searchParams: Partial<FilterFormType>) => {
  console.log('接收到搜索参数：', searchParams);
  // 更新筛选条件
  Object.assign(filterForm, searchParams);
  // 重置页码并获取数据
  currentPage.value = 1;
  getList();
};

// 重置筛选
const resetFilter = () => {
  // 重置筛选条件
  (Object.keys(filterForm) as Array<keyof FilterFormType>).forEach((key) => {
    filterForm[key] = '';
  });
  // 重置页码并获取数据
  currentPage.value = 1;
  getList();
};

// 新增员工
const handleAdd = () => {
  dialogType.value = 'add';
  dialogVisible.value = true;
  Object.assign(form, {
    userId: '',
    deptId: undefined,
    deptName: '',
    userName: '',
    nickName: '',
    phonenumber: '',
    email: '',
    sex: '0'
  });
};

// 处理部门选择变化
const handleDeptChange = (deptId: number) => {
  // 根据选择的部门ID找到对应的部门名称
  const findDeptName = (depts: Department[], id: number): string => {
    for (const dept of depts) {
      if (dept.deptId === id) {
        return dept.deptName;
      }
      if (dept.children && dept.children.length > 0) {
        const found = findDeptName(dept.children, id);
        if (found) return found;
      }
    }
    return '';
  };

  form.deptName = findDeptName(deptList.value, deptId);
};

// 编辑员工
const handleEdit = (row: Employee) => {
  dialogType.value = 'edit';
  dialogVisible.value = true;
  Object.assign(form, {
    userId: row.userId,
    deptId: row.deptId,
    deptName: row.dept?.deptName || '', // 使用部门对象中的部门名称
    userName: row.userName,
    nickName: row.nickName,
    phonenumber: row.phonenumber,
    email: row.email,
    sex: row.sex
  });
};

// 删除员工
const handleDelete = async (row: Employee) => {
  try {
    await ElMessageBox.confirm('确认要删除该员工吗？', '提示', {
      type: 'warning'
    });
    const res = (await deleteEmployee(row.userId)) as unknown as CommonResponse;
    if (res.code === 200) {
      ElMessage.success('删除成功');
      getList();
    } else {
      ElMessage.error(res.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除员工失败:', error);
      ElMessage.error('删除员工失败');
    }
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // 验证必填字段
      if (!form.deptId) {
        ElMessage.error('请选择所属部门');
        return;
      }

      try {
        if (dialogType.value === 'add') {
          const { userId, ...addParams } = form;
          const res = (await addEmployee(addParams as AddEmployeeParams)) as unknown as CommonResponse;
          if (res.code === 200) {
            ElMessage.success('新增成功');
            dialogVisible.value = false;
            getList();
          } else {
            ElMessage.error(res.msg || '新增失败');
          }
        } else {
          const editParams: EditEmployeeParams = {
            userId: form.userId as number,
            deptId: form.deptId,
            userName: form.userName,
            nickName: form.nickName,
            phonenumber: form.phonenumber,
            email: form.email,
            sex: form.sex
          };
          const res = (await editEmployee(editParams)) as unknown as CommonResponse;
          if (res.code === 200) {
            ElMessage.success('编辑成功');
            dialogVisible.value = false;
            getList();
          } else {
            ElMessage.error(res.msg);
          }
        }
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '新增失败' : '编辑失败');
      }
    }
  });
};

// 初始化
onMounted(() => {
  getList();
  getDeptList();
});
</script>

<style lang="scss" scoped>
.staff-manage {
  padding: 20px;
  min-height: calc(100vh - 40px);

  .operation-section {
    margin-bottom: 20px;
    display: flex;
    gap: 12px;
  }

  .table-section {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .custom-table {
      :deep(.el-table__header) {
        th {
          background-color: #f5f7fa;
          color: #606266;
          font-weight: 600;
        }
      }

      :deep(.el-table__row) {
        &:hover {
          td {
            background-color: #f5f7fa;
          }
        }
      }
    }
  }

  .pagination-section {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    padding: 16px 0;

    .custom-pagination {
      :deep(.el-pagination__total) {
        margin-right: 16px;
      }

      :deep(.el-pagination__sizes) {
        margin-right: 16px;
      }
    }
  }
}

.staff-dialog {
  :deep(.el-dialog__body) {
    padding: 20px 30px;
  }

  .staff-form {
    max-width: 500px;
    margin: 0 auto;

    .w-full {
      width: 100%;
    }
  }
}
</style>
